<template>
  <div class="main">
    <div class="title">
      <div>图书管理</div>
      <div>
        <!-- <el-upload
          action=""
          :on-change="handleChange"
          :show-file-list="false"
          :auto-upload="false"
          :multiple="false"
          accept=".xlsx,.xls"
          :limit="1"
        >
          <el-button type="primary" :icon="CirclePlus" @click="addBook"
            >批量加入图书</el-button
          >
        </el-upload> -->

        <el-button type="primary" :icon="CirclePlus" @click="addBook"
          >新增图书</el-button
        >
      </div>
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>搜索内容：</span>
        <el-input v-model="query.queryName" style="width: 200px" />
      </div>
      <div class="label-input">
        <span>选择区域：</span>
        <el-select
          v-model="query.areaId"
          placeholder="请选择区域"
          style="width: 200px"
          @change="changeArea"
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="label-input">
        <span>选择图书柜：</span>
        <el-select
          v-model="query.cabinetId"
          placeholder="请选择图书柜"
          style="width: 200px"
        >
          <el-option
            v-for="item in cabinetList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>请选择状态：</span>
        <el-select
          v-model="query.state"
          placeholder="请选择状态"
          style="width: 200px"
        >
          <el-option label="在库" :value="0" />
          <el-option label="借出" :value="1" />
        </el-select>
      </div>
      <el-button class="search-btn" @click="getTabelData">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div class="cut-line"></div>
    <el-table
      :data="tabelData"
      height="350"
      style="width: 100%"
      border
      v-loading="loading"
      :header-cell-style="headerStyle"
      row-key="id"
    >
      <el-table-column type="index" align="center" label="#" width="50" />
      <el-table-column
        prop="name"
        align="center"
        label="图书名称"
        width="200"
      />
      <el-table-column
        prop="author"
        align="center"
        label="作者名称"
        width="200"
      />
      <el-table-column
        prop="positionName"
        align="center"
        label="图书位置"
        width="150"
      />
      <el-table-column
        prop="rfid"
        align="center"
        label="RFID条码"
        width="100"
      />
      <el-table-column prop="state" align="center" label="状态" width="100" />
      <el-table-column
        prop="borrowTime"
        align="center"
        label="借出时间"
        width="200"
      >
        <template v-slot="scope">
          <div>{{ scope.row.state == "在库" ? "" : scope.row.borrowTime }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="remark" align="center" label="备注" width="200" />
      <el-table-column align="center" label="操作" width="300" fixed="right">
        <template v-slot="scope">
          <div class="table-buts">
            <el-button type="primary" @click="lookBorrowlog(scope.row.id)"
              >查看借阅记录</el-button
            >
            <el-button
              style="background-color: #3d839c; color: #fff"
              @click="updateBook(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" @click="deleteBook(scope.row.id)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="tabelDataTotal"
        :page-size="query.pageSize"
        :current-page="query.pageNum"
        @update:current-page="currentPageChange"
      />
    </div>
    <!-- 添加、修改弹窗 -->
    <el-dialog v-model="dialogTableVisible" :title="title" width="400">
      <div class="dialog-win">
        <el-form
          ref="ruleFormRef"
          :model="table"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item label="图书名称：" prop="name">
            <el-input v-model="table.name" style="width: 240px" />
          </el-form-item>
          <el-form-item label="图书作者：" prop="author">
            <el-input v-model="table.author" style="width: 240px" />
          </el-form-item>
          <el-form-item label="RFID条码：" prop="rfid">
            <el-input v-model="table.rfid" style="width: 240px" />
          </el-form-item>
          <el-form-item label="区域：" prop="areaId">
            <el-select
              v-model="table.areaId"
              placeholder="请选择区域"
              style="width: 240px"
              @change="changeWinArea"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图书柜：" prop="cabinetId">
            <el-select
              v-model="table.cabinetId"
              placeholder="请选择图书柜"
              style="width: 240px"
              @change="changeWinCabinet"
            >
              <el-option
                v-for="item in cabinetWinList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="柜格：" prop="latId">
            <el-select
              v-model="table.latId"
              placeholder="请选择柜格"
              style="width: 240px"
            >
              <el-option
                v-for="item in latWinList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input v-model="table.remark" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleFormRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleFormRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogBorrowTableVisible" :title="title" width="600">
      <div class="dialog-win">
        <el-table
          :data="borrowList"
          height="400"
          style="width: 100%"
          border
          :header-cell-style="headerStyle"
        >
          <el-table-column type="index" align="center" label="#" width="50" />
          <el-table-column
            prop="personName"
            align="center"
            label="读者姓名"
            width="200"
          />
          <el-table-column
            prop="type"
            align="center"
            label="操作类型"
            width="100"
          />
          <el-table-column prop="operateTime" align="center" label="操作时间" />
        </el-table>
      </div>
    </el-dialog>
    <!-- 批量添加图书 -->
    <el-dialog v-model="dialogAddTableVisible" :title="title" width="300">
      <div class="dialog-win">
        <div>
          <div class="search-bar">
            <span>图书类型：</span>
            <el-select
              v-model="table.areaId"
              placeholder="请选择区域"
              style="width: 240px"
              @change="changeWinPosition"
            >
              <el-option label="全部" :value="0" />
              <el-option label="已选择位置" :value="1" />
              <el-option label="未选择位置" :value="2" />
            </el-select>
          </div>
          <div class="search-bar">
            <span>请选择区域：</span>
            <el-select
              v-model="table.areaId"
              placeholder="请选择区域"
              style="width: 240px"
              @change="changeWinArea"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <div class="search-bar">
            <span>请选择图书柜：</span>
            <el-select
              v-model="table.cabinetId"
              placeholder="请选择图书柜"
              style="width: 240px"
              @change="changeWinCabinet"
            >
              <el-option
                v-for="item in cabinetWinList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <div class="search-bar">
            <span>请选择柜格：</span>
            <el-select
              v-model="table.latId"
              placeholder="请选择柜格"
              style="width: 240px"
            >
              <el-option
                v-for="item in latWinList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <el-button class="search-btn" @click="addPosition"
            >添加位置信息</el-button
          >
        </div>
        <el-table
          :data="fileExcelList"
          height="800"
          style="width: 100%"
          border
          :header-cell-style="headerStyle"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="index"
            align="center"
            label="EXCEL列号"
            width="50"
          />
          <el-table-column
            prop="name"
            align="center"
            label="图书名称"
            width="200"
          />
          <el-table-column
            prop="author"
            align="center"
            label="作者名称"
            width="200"
          />
          <el-table-column
            prop="rfid"
            align="center"
            label="RFID条码"
            width="100"
          />
          <el-table-column
            prop="positionName"
            align="center"
            label="位置"
            width="100"
          />
          <el-table-column
            prop="remark"
            align="center"
            label="备注"
            width="200"
          />
        </el-table>
        <div class="from-but">
          <el-button type="warning" @click="submit(ruleFormRef)"
            >确定</el-button
          >
          <el-button type="info" @click="clearAddBooks">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { CirclePlus } from "@element-plus/icons-vue";
import message from "@/util/alert.js";
import { ref, reactive, onMounted } from "vue";
import { getAllAreaListApi } from "@/api/areaApi.js";
import {
  getAllCabinetListApi,
  getCabinetLatListApi,
} from "@/api/cabinetApi.js";
import {
  getBookListApi,
  updateBookApi,
  addBookApi,
  addBookListApi,
  getBorrowByBookApi,
  deleteBookApi,
} from "@/api/booksApi.js";
import { useConfigStore } from "@/stores";
const configStore = useConfigStore();
// 查询参数
const query = reactive({
  cabinetId: "",
  areaId: "",
  queryName: "",
  state: "",
  isDeleted: 0,
  pageNum: 1,
  pageSize: 10,
});
const tabelDataTotal = ref(0);
const loading = ref(false);
const tabelData = ref([]);
// 表单头部样式
const headerStyle = () => {
  return {
    backgroundColor: "#a0cfff",
    color: "#000000",
    padding: "8px 0px",
  };
};
// 当前页改变
const currentPageChange = (num) => {
  query.pageNum = num;
  getTabelData();
};
// 选择图书柜
const cabinetList = ref([]);
const changeArea = async () => {
  query.cabinetId = "";
  let res = await getAllCabinetListApi({
    areaId: query.areaId,
  });
  cabinetList.value = res.data;
};
// 获取柜子列表
const getTabelData = async () => {
  loading.value = true;
  let res = await getBookListApi(query);
  tabelDataTotal.value = res.data.total;
  tabelData.value = res.data.rows;
  loading.value = false;
};
const borrowList = ref([]);
const dialogBorrowTableVisible = ref(false);
// 查看书籍的借阅记录
const lookBorrowlog = async (id) => {
  let res = await getBorrowByBookApi(id);
  borrowList.value = res.data;
  if (borrowList.value.length == 0) {
    message.info("暂无任何借阅记录");
  } else {
    title.value = "借阅记录";
    dialogBorrowTableVisible.value = true;
  }
};
const cabinetWinList = ref([]);
// 选择位置
const changeWinPosition = () => {};
// 弹窗选择区域
const changeWinArea = async (flag = true) => {
  if (flag) {
    table.value.cabinetId = "";
    table.value.latId = "";
  }

  let res = await getAllCabinetListApi({
    areaId: table.value.areaId,
  });
  cabinetWinList.value = res.data;
};
const latWinList = ref([]);
// 弹窗选择图书柜
const changeWinCabinet = async (flag = true) => {
  if (flag) {
    table.value.latId = "";
  }

  let res = await getCabinetLatListApi(table.value.cabinetId);
  latWinList.value = res.data;
};
// 添加图书
const addBook = () => {
  table.value = {
    author: "",
    latId: "",
    name: "",
    remark: "",
    rfid: "",
    areaId: "",
    cabinetId: "",
  };
  title.value = "添加图书";
  dialogTableVisible.value = true;
};
const dialogAddTableVisible = ref(false);
// 批量添加图书
const handleChange = (file, fileList) => {
  const fileContent = file.raw;
  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
  if (fileContent) {
    if (fileType === "xlsx" || fileType === "xls") {
      importfile(fileContent);
    } else {
      message.error("附件格式错误，请重新上传!");
    }
  } else {
    message.error("请上传附件！");
  }
};
// 取消批量添加
const clearAddBooks = () => {
  dialogAddTableVisible.value = false;
  table.value = {
    latId: "",
    areaId: "",
    cabinetId: "",
    positionName: "", //位置名称
    position: 0, //0 全部 1 已选择位置 2 未选择位置
  };
};
const multipleSelection = ref([]);
// 选择需要添加位置信息的图书
const handleSelectionChange = (arr) => {
  multipleSelection.value = arr;
  arr.forEach((el) => {
    el.positionName = table.value.positionName;
    el.latId = table.value.latId;
  });
};
// 添加位置信息
const addPosition = () => {
  if (table.value.positionName) {
    // 添加信息
    multipleSelection.value.forEach((el) => {
      el.positionName = table.value.positionName;
      el.latId = table.value.latId;
    });
  } else {
    message.error("位置信息未选择");
  }
};
const fileExcelList = ref([]);
const importfile = (obj) => {
  fileExcelList.value = [];
  const reader = new FileReader();
  reader.readAsArrayBuffer(obj);
  reader.onload = async function () {
    const buffer = reader.result;
    const bytes = new Uint8Array(buffer);
    const length = bytes.byteLength;
    let binary = "";
    for (let i = 0; i < length; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    const wb = read(binary, {
      type: "binary",
    });
    const outdata = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
    for (let i = 0; i < outdata.length; i++) {
      fileExcelList.value.push({
        index: i + 2,
        name: row.图书名称 || "",
        author: row.作者名称 || "",
        rfid: row.RFID条码 || "",
        remark: row.备注,
        positionName: "",
        latId: "",
      });
    }
    title.value = "批量添加图书";
    dialogAddTableVisible.value = true;
    table.value = {
      latId: "",
      areaId: "",
      cabinetId: "",
      positionName: "", //位置名称
      position: 0, //0 全部 1 已选择位置 2 未选择位置
    };
  };
};
// 修改图书信息
const updateBook = (row) => {
  table.value = JSON.parse(JSON.stringify(row));
  title.value = "修改图书信息";
  changeWinArea(false);
  changeWinCabinet(false);
  table.value.state = table.value.state == "在库" ? 0 : 1;
  table.value.isDeleted = table.value.isDeleted == "正常" ? 0 : 1;
  console.log(table.value);
  dialogTableVisible.value = true;
};
// 删除图书
const deleteBook = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否删除此图书`,
    ok: async () => {
      await deleteBookApi(id);
      message.success(`删除成功`);
      getTabelData();
    },
  });
};
// 重置
const reset = () => {
  Object.assign(query, {
    cabinetId: "",
    queryName: "",
    state: "",
    areaId: "",
    pageNum: 1,
    pageSize: 10,
    isDeleted: 0,
  });
  getTabelData();
};
// 弹窗
const table = ref({});
const dialogTableVisible = ref(false);
const title = ref("");
const ruleFormRef = ref(null);
// 添加、修改的规则
const rules = reactive({
  name: [
    { required: true, message: "请输入图书名称", trigger: "blur" },
    { min: 2, max: 30, message: "图书名称长度为2-30", trigger: "blur" },
  ],
  author: [
    { required: true, message: "请输入作者名称", trigger: "blur" },
    { min: 2, max: 20, message: "图书名称长度为2-20", trigger: "blur" },
  ],
  rfid: [{ required: true, message: "请输入RFID编号", trigger: "blur" }],
  areaId: [{ required: true, message: "请选择区域", trigger: "change" }],
  cabinetId: [{ required: true, message: "请选择图书柜", trigger: "change" }],
  latId: [{ required: true, message: "请选择柜格", trigger: "change" }],
});
// 提交表单
const submit = async (ruleForm) => {
  if (!ruleForm) return;
  await ruleForm.validate(async (valid, fields) => {
    if (valid) {
      if (title.value == "添加图书") {
        await addBookApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("添加图书成功");
      } else if (title.value == "修改图书信息") {
        await updateBookApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("修改图书信息成功");
      }
    }
  });
};
// 重置表单
const resetForm = (ruleForm) => {
  ruleForm.resetFields();
  dialogTableVisible.value = false;
  table.value = {};
};

const areaList = ref([]);
const areabyIdObj = ref({});
onMounted(async () => {
  getTabelData();
  if (!configStore.areaList) {
    let res = await getAllAreaListApi();
    areaList.value = res.data;
    configStore.areaList = res.data;
  } else {
    areaList.value = configStore.areaList;
  }
  areaList.value.forEach((el) => {
    areabyIdObj.value[el.name] = el.id;
  });
});
</script>
      <style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  padding: 10px 20px;
  .title {
    font-size: 20px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
  }
}
.search-bar {
  margin-top: 20px;
  display: flex;
  align-items: center;
  height: 30px;
  .search-btn {
    background-color: #79bbff;
    color: #ffffff;
  }
  .el-button {
    height: 28px;
  }
}
.label-input {
  display: flex;
  color: #aaaaaa;
  height: 30px;
  align-items: center;
  margin-right: 20px;
  font-weight: 550;
  .el-input {
    border: none;
    height: 30px;
  }
}
.cut-line {
  margin-top: 30px;
  height: 1px;
  background-color: #cdd0d6;
}

.pagination {
  display: flex;
  justify-content: center;

  .el-pagination {
    margin: auto 0;
    margin-top: 10px;
  }
}
:deep(.el-table) {
  margin-top: 20px;
  .el-table__cell {
    padding: 2px;
  }
}
</style>